import { login, logout, getInfo, getMenudata } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserData, setUserData, removeUserData } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    user_data: getUserData(),
    userInfo:'',
    routes: [], // 动态路由
  }
}

const state = getDefaultState()
state.routes = JSON.parse(localStorage.getItem('routes'));
if(localStorage.getItem('userInfo')){
  state.userInfo = JSON.parse(localStorage.getItem('userInfo'));
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_DATA: (state, user_data) => {
    state.user_data = user_data
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes // 动态路由
    localStorage.setItem('routes', JSON.stringify(routes))
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo // 用户信息
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), upass: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)// vuex存储token
        setToken(data.token)// cookie存储token
        commit('SET_USER_DATA', data.user_data)// vuex存储user_data
        setUserData(data.user_data)// cookie存储user_data
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
      //   const { data } = response
        var userInfo ={
          // roles: ['admin'],
          // introduction: 'I am a super administrator',
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
          name: '超级管理员',
        }
        if (!userInfo) {
          return reject('验证失败，请重新登录。')
        }

        // const { name, avatar, roles} = data
        /**
                * 获取异步路由后加入404路由能解决刷新后【丢失路由跳转404页面】问题
                （因为异步获取路由优先级比静态路由表低，导致404路由在异步添加的路由之前）
                */
        commit('SET_USERINFO', userInfo)
        // commit('SET_AVATAR', avatar)
        resolve(userInfo)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // 登出
  logout({ commit, state }) {
    /* 无登出接口*/
    return new Promise((resolve, reject) => { // 如果后端有退出接口写在下面即可，这里直接退出也没问题
       removeToken() // 必须先移除token
       removeUserData() // 必须先移除user_data
       resetRouter()
       commit('RESET_STATE')
       resolve()
     })
     /* 有登出接口*/
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // 必须先移除token
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
  //动态添加路由
  getMenudata({ commit, state }){
    return new Promise((resolve, reject) => {
      getMenudata({}).then(response => {
        commit('SET_ROUTES',response.data)// 动态菜单
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 必须先移除token
      removeUserData() // 必须先移除user_data
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
